package de.slothsoft.commons.swing;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.Icon;

public abstract class AbstractResizableIcon implements Icon {

	protected float originalAlpha = 1.0f;
	private int width;
	private int height;

	public AbstractResizableIcon() {
		this.width = getOriginalWidth();
		this.height = getOriginalHeight();
	}

	/**
	 * Returns the original width of the image
	 */

	public abstract int getOriginalWidth();

	/**
	 * Returns the original height of the image
	 */

	public abstract int getOriginalHeight();

	/*
	 * (non-Javadoc)
	 */

	@Override
	public int getIconHeight() {
		return this.height;
	}

	/*
	 * (non-Javadoc)
	 */

	@Override
	public int getIconWidth() {
		return this.width;
	}

	/**
	 * Set the size of the icon.
	 */

	public void setSize(Dimension dim) {
		this.width = dim.width;
		this.height = dim.height;
	}

	/*
	 * (non-Javadoc)
	 */

	@Override
	public void paintIcon(Component c, Graphics g, int x, int y) {
		Graphics2D g2d = (Graphics2D) g.create();
		g2d.translate(x, y);

		double coef1 = this.width / (double) getOriginalWidth();
		double coef2 = this.height / (double) getOriginalHeight();
		double coef = Math.min(coef1, coef2);
		g2d.scale(coef, coef);
		paint(g2d);
		g2d.dispose();
	}

	/**
	 * Draw the icon.
	 * 
	 * @param g
	 *            - graphics context
	 */

	public abstract void paint(Graphics2D g);
}
